package io.renren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.entity.ShoppingCartEntity;
import io.renren.common.entity.UserEntity;
import io.renren.common.exception.RenException;
import io.renren.common.utils.UserUtils;
import io.renren.dao.ShoppingCartDao;
import io.renren.dao.UserDao;
import io.renren.dto.ShoppingCartDTO;
import io.renren.service.ShoppingCartService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 购物车
 *
 * @author MaYun
 * @since 1.0.0 2022-08-17
 */
@Service
public class ShoppingCartServiceImpl extends CrudServiceImpl<ShoppingCartDao, ShoppingCartEntity, ShoppingCartDTO> implements ShoppingCartService {

    @Autowired
    private ShoppingCartDao shoppingCartDao;
    @Autowired
    private UserUtils userUtils;
    @Autowired
    private UserDao userDao;

    @Override
    public QueryWrapper<ShoppingCartEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<ShoppingCartEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "user_id", id);

        return wrapper;
    }


    @Override
    public ShoppingCartEntity add2shoppingCart(ShoppingCartDTO shoppingCartDTO) {

        Long userId = userUtils.getUserId();
        shoppingCartDTO.setUserId(userId);

        UserEntity user = userDao.getUserByUserId(userId);
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getIsCertified()) || 0 == user.getIsCertified()) {
            throw new RenException("用户未认证!请通知管理员认证。");
        }

        // 查询当前商品或者套餐是否在购物车中
        Long dishId = shoppingCartDTO.getDishId();
        LambdaQueryWrapper<ShoppingCartEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCartEntity::getUserId, userId);

        if (dishId != null) {
            // 添加到购物车的是商品
            queryWrapper.eq(ShoppingCartEntity::getDishId, dishId);
        } else {
            // 添加到购物车的是套餐
            queryWrapper.eq(ShoppingCartEntity::getSetmealId, shoppingCartDTO.getSetmealId());
        }

        ShoppingCartEntity shoppingCart = shoppingCartDao.selectOne(queryWrapper);

        Integer reqNumber = shoppingCartDTO.getNumber() == null ? 1 : shoppingCartDTO.getNumber();

        if (shoppingCart != null) {
            // 已经存在，数量累加
            shoppingCart.setNumber(shoppingCart.getNumber() + reqNumber);
            shoppingCartDao.updateById(shoppingCart);
        } else {
            // 不存在，直接插入
            shoppingCart = new ShoppingCartEntity();
            BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);

            // 如果传入数量为空或小于 1，默认设为 1
            shoppingCart.setNumber(reqNumber <= 0 ? 1 : reqNumber);

            shoppingCartDao.insert(shoppingCart);
        }

        return shoppingCart;
    }


    @Override
    public ShoppingCartEntity subFromShoppingCart(ShoppingCartDTO shoppingCartDTO) {

        Long userId = userUtils.getUserId();

        LambdaQueryWrapper<ShoppingCartEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(shoppingCartDTO.getDishId() != null,ShoppingCartEntity::getDishId,shoppingCartDTO.getDishId());
        queryWrapper.eq(shoppingCartDTO.getSetmealId() != null,ShoppingCartEntity::getSetmealId,shoppingCartDTO.getSetmealId());
        queryWrapper.eq(ShoppingCartEntity::getUserId,userId);
        ShoppingCartEntity one = shoppingCartDao.selectOne(queryWrapper);
        if (one.getNumber() == 1){
            shoppingCartDao.deleteById(one);
        }
        Integer number = one.getNumber();
        one.setNumber(number-1);
        shoppingCartDao.updateById(one);
        return one;
    }
    @Override
    public ShoppingCartEntity updateShoppingCart(ShoppingCartDTO shoppingCartDTO) {

        ShoppingCartEntity one = shoppingCartDao.selectById(shoppingCartDTO.getId());
        if (one == null) {
            throw new RenException("购物车中不存在该商品或套餐，无法更新");
        }
        // 更新数量（小于等于0则删除）
        Integer reqNumber = shoppingCartDTO.getNumber();
        if (reqNumber == null || reqNumber <= 0) {
            shoppingCartDao.deleteById(one.getId());
            return null;
        } else {
            one.setNumber(reqNumber);
            shoppingCartDao.updateById(one);
            return one;
        }
    }


    @Override
    public void cleanShoppingCart() {
        Long id = userUtils.getUserId();
        LambdaQueryWrapper<ShoppingCartEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCartEntity::getUserId,id);
        shoppingCartDao.delete(queryWrapper);
    }

    @Override
    public List<ShoppingCartEntity> ShoppingCartList() {
        Long id = userUtils.getUserId();
        LambdaQueryWrapper<ShoppingCartEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCartEntity::getUserId,id);
        queryWrapper.orderByAsc(ShoppingCartEntity::getCreateDate);
        return shoppingCartDao.selectList(queryWrapper);
    }
}